import $ from 'jquery';
import Config from '../config/Config';

var wx = require('weixin-js-sdk');

/**
 * 获取签名信息
 * @returns {Promise}
 */
const getAssgin = function () {
  let APIUrl = Config.getAPIUrl('wx_sign');

  let promise = new Promise(function (resolve, reject) {
    let url = JSON.stringify({'url': location.href});

    $.ajax({
      url: APIUrl,
      data: url,
      type: 'post',
      cache: false,
      contentType: 'application/json;charset=utf-8',
      dataType: 'json',
      headers: {
        Accept: 'application/json'
      },
      beforeSend: (request) => {
        request.setRequestHeader('X-iChangTou-Json-Api-Token', Config.getApiToken());
      },
      success: resolve,
      error: reject
    });
  })
  return promise;
}

/**
 * 签名
 * @param data
 */
const assgin = function (data) {
  wx.config({
    appId: data.wechat_appid,
    timestamp: data.timestamp,
    nonceStr: data.nonceStr,
    signature: data.signature,
    jsApiList: [
      'onMenuShareTimeline',
      'onMenuShareAppMessage',
      'onMenuShareQQ',
      'onMenuShareWeibo',
      'chooseWXPay'
    ]
  });

  wx.ready(() => {
    shareConfig({shareTitle: '', shareDesc: ''})
  });
}

/**
 * 设置分享成功
 */
const onShareSuccess = function (channel) {
  let APIUrl = Config.getAPIUrl('post_share');
  APIUrl = APIUrl.replace(':parentId', '111111111111');
  let promise = new Promise(function (resolve, reject) {
    $.ajax({
      url: APIUrl, // 授权登录
      type: 'POST',
      cache: false,
      contentType: 'application/json;charset=utf-8',
      dataType: 'json',
      headers: {
        Accept: 'application/json'
      },
      beforeSend: (request) => {
        request.setRequestHeader('X-iChangTou-Json-Api-Token', Config.getApiToken());
        request.setRequestHeader('X-iChangTou-Json-Api-User', JSON.parse(localStorage.getItem('ict48-user-info')).userId);
      },
      success: resolve,
      error: reject
    });
  })
  return promise
}

window.onShareSuccess = onShareSuccess

/**
 * 设置分享失败
 * @param channel
 */
const onShareFailure = function (channel) {
  //
}
window.onShareFailure = onShareFailure

/**
 * 设置分享
 */
const shareConfig = function ({shareTitle, shareDesc}) {
  const user = JSON.parse(localStorage.getItem('ict48-user-info'));
  let imgUrl = user.headImage;
  let desc = '看看他们怎么说';
  let title = '我是默认辩题';
  let link = getShareLink();

  // const onShareSuccess = onShareSuccess;
  // const onShareFailure = onShareFailure;
  // const me = this
  if (!imgUrl) {
    imgUrl = Config.getAPIDomain() + 'build/share-icon.png';
  }

  // let timelineOpt = {
  //     title,
  //     desc,
  //     link,
  //     imgUrl,
  //     success: () => {
  //       window.onShareSuccess('朋友圈');
  //     },
  //     cancel: () => {
  //       window.onShareFailure('朋友圈');
  //     }
  //   }, messageOpt = {
  //     title,
  //     desc,
  //     link,
  //     imgUrl,
  //     success: () => {
  //       onShareSuccess('消息');
  //     },
  //     cancel: () => {
  //       onShareFailure('消息');
  //     }
  //   }, QQOpt = {
    //   title,
    //   desc,
    //   link,
    //   imgUrl,
    //   success: () => {
    //     onShareSuccess('QQ');
    //   },
    //   cancel: () => {
    //     onShareFailure('QQ');
    //   }
    // }, weiboOpt = {
    //   title,
    //   desc,
    //   link,
    //   imgUrl,
    //   success: () => {
    //     onShareSuccess('weibo');
    //   },
    //   cancel: () => {
    //     onShareFailure('weibo');
    //   }
    // };

  // QQ的分享链接单独设置（为了能在QQ中打开）
//   QQOpt.link = getQQShareLink();
//
//   wx.onMenuShareTimeline(timelineOpt);
//   wx.onMenuShareAppMessage(messageOpt);
//   wx.onMenuShareQQ(QQOpt);
//   wx.onMenuShareWeibo(weiboOpt);
// }


/**
 * 获取分享到QQ的链接
 */
const getQQShareLink = function () {
  let link = Config.getHtmlUrl() + '?ICT48=' + Config.getIct48Id();

  return link;
}

/**
 * 获取分享链接
 * @returns {string}
 */
const getShareLink = function () {
  let redirectUri = Config.getHtmlUrl();
  let link = '';
  // let userInfo = JSON.parse(localStorage.getItem('ict48-user-info')) || {};

  redirectUri = redirectUri + '?ICT48=' + Config.getIct48Id();

  // console.log('share link= ', redirectUri);

  redirectUri = encodeURIComponent(redirectUri);

  link = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + Config.getAppId() +
    '&redirect_uri=' + redirectUri +
    '&response_type=code' +
    '&scope=' + 'snsapi_base' +
    '&state=minic#wechat_redirect';

  return link;
}

/**
 * 初始化微信
 */
const initWx = function () {
  getAssgin()
    .then(assgin)
    .catch(function () {
      console.log('设置微信失败')
    })
}

export {
  initWx
}
